<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/20
 * Time: 21:35
 */

namespace App\Console\Commands;

use App\Models\ArticleArchieve;
use Illuminate\Console\Command;
use App\Models\User;
use App\Models\Topic;
use Carbon\Carbon;
use DB;

class CalculateArticleArchieve extends Command
{
    protected $signature = 'dspstack:calculate-article-archieve';
    protected $description = 'Calculate article archieve';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $this->calculateArticleArchieve();
    }

    protected function calculateArticleArchieve()
    {
        $blog_archieve_list = ArticleArchieve::orderBy('archieved_at','DESC')
                                ->take(1)->get();
        if($blog_archieve_list && count($blog_archieve_list))
        {
            //
            $start_time = date_format(Carbon::createFromTimeString($blog_archieve_list[0]->archieved_at.'-00 00:00:00')->addMonth(), 'Y-m');
        }
        else
        {
            $start_time = '1900-00';
        }

        $article_list = Topic::select('id','user_id', 'created_at')
            ->withoutDraft()
            ->onlyArticle()
            ->where('created_at', '>=', $start_time)
            ->where('created_at', '<', date_format(Carbon::now(), 'Y-m'))
            ->get();

        $article_archieve = [];
        foreach ($article_list as $key => $article)
        {
            $date = date_format(Carbon::createFromTimeString($article['created_at']), 'Y-m');
            $a_key = $article['user_id'].'-'.$date;
            if(isset($article_archieve[$a_key]))
            {
                $a_count = $article_archieve[$a_key]['article_count'];
                $article_archieve[$a_key]['article_count'] = intval($a_count) + 1;
                $a_ids = $article_archieve[$a_key]['article_ids'];
                $article_archieve[$a_key]['article_ids'] = $a_ids.'-'.$article->id;
            }
            else
            {
                $article_archieve[$a_key]['user_id'] =  $article->user_id;
                $article_archieve[$a_key]['archieved_at'] =  $date;
                $article_archieve[$a_key]['article_count'] = 1;
                $article_archieve[$a_key]['article_ids'] = $article->id;
            }

        }

        foreach ($article_archieve as $key => $achieve)
        {
            $a_a = new ArticleArchieve();
            $a_a->user_id = $achieve['user_id'];
            $a_a->article_count = $achieve['article_count'];
            $a_a->article_ids = $achieve['article_ids'];
            $a_a->archieved_at = $achieve['archieved_at'];

            $a_a->save();
        }
        $this->info('Done!');
    }
}